package com.example.administrator.im.ui.activity;

import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.design.widget.TextInputLayout;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.administrator.im.R;
import com.example.administrator.im.json.ResultJson;
import com.example.administrator.im.utils.DialogUtils;
import com.example.administrator.im.utils.EMUtils;
import com.example.administrator.im.utils.HttpUtils;
import com.google.gson.Gson;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * create:2018/10/2 16:15
 * author: 姚鸿杰
 **/
public class RegisterActivity extends AppCompatActivity {

    private final String TAG = "RegisterActivity";

    private EventHandler eventHandler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理成功得到验证码的结果
                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                        }
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
//                            Log.e(TAG, "验证码对的");
                            DialogUtils.setDialog(RegisterActivity.this, R.layout.loading);
                            DialogUtils.showDialog();

                            isUserExist(et_phone.getText().toString());

                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
//                            Log.e(TAG, "验证码不对的");
                            til_auto_code.setErrorEnabled(true);
                            til_auto_code.setError("验证码不对");
                        }
                    }
                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
                    return false;
                }
            }).sendMessage(msg);
        }
    };

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Button btn = (Button) msg.obj;
            btn.setText(String.valueOf(msg.arg1));
            if (msg.arg1 == 0) {
                btn.setClickable(true);
                btn.setBackgroundResource(R.drawable.send_btn);
                btn.setText("获取验证码");
            }

        }
    };

    private TextInputLayout til_phone;
    private TextInputLayout til_auto_code;
    private TextInputLayout til_first_password;
    private TextInputLayout til_second_password;

    private EditText et_phone;
    private EditText et_auto_code;
    private EditText et_first_password;
    private EditText et_second_password;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();

        SMSSDK.registerEventHandler(eventHandler);
        EventBus.getDefault().register(this);
    }

    private void initView() {
        til_phone = (TextInputLayout) findViewById(R.id.til_phone);
        til_auto_code = (TextInputLayout) findViewById(R.id.til_auto_code);
        til_first_password = (TextInputLayout) findViewById(R.id.til_first_password);
        til_second_password = (TextInputLayout) findViewById(R.id.til_second_password);

        et_phone = (EditText) findViewById(R.id.et_phone);
        et_auto_code = (EditText) findViewById(R.id.auto_code);
        et_first_password = (EditText) findViewById(R.id.first_password);
        et_second_password = (EditText) findViewById(R.id.second_password);

        et_phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                til_phone.setErrorEnabled(false);
            }
        });
        et_auto_code.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                til_auto_code.setErrorEnabled(false);
            }
        });
        et_first_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                til_first_password.setErrorEnabled(false);
            }
        });
        et_second_password.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                til_second_password.setErrorEnabled(false);
            }
        });
    }

    /**
     * 获取验证码
     *
     * @param v
     */
    public void obtainAutoCode(View v) {

        String phone = et_phone.getText().toString();
        boolean isMobile = isMobile(phone);
        if (!isMobile) {
            til_phone.setErrorEnabled(true);
            til_phone.setError("请输入正确的手机号码");
            return;
        }
        //请求验证码，其中country表示国家代码，如“86”；phone表示手机号码，如“13800138000”
        SMSSDK.getVerificationCode("86", phone);
        Button btn = (Button) v;
        timeing(btn);
    }

    //计时
    private void timeing(final Button btn) {
        btn.setClickable(false);
        btn.setBackgroundResource(R.color.default_color);

        new Thread() {
            @Override
            public void run() {
                super.run();
                int totalTime = 60;
                for (int i = 0; i < totalTime; i++) {
                    Message msg = new Message();
                    msg.obj = btn;
                    msg.arg1 = totalTime - (i + 1);
                    handler.sendMessage(msg);
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
    }

    //注册           未做账号存在提示
    public void register(View v) {

        til_phone.setErrorEnabled(false);
        til_auto_code.setErrorEnabled(false);
        til_first_password.setErrorEnabled(false);
        til_second_password.setErrorEnabled(false);

        String phone = et_phone.getText().toString();
        String auto_code = et_auto_code.getText().toString();
        String first_password = et_first_password.getText().toString();
        String second_password = et_second_password.getText().toString();

        //判断手机号码
        if (TextUtils.isEmpty(phone)) {
            til_phone.setErrorEnabled(true);
            til_phone.setError("手机号码不能为空");
            return;
        }

        //判断验证码
        if (TextUtils.isEmpty(auto_code)) {
            til_auto_code.setErrorEnabled(true);
            til_auto_code.setError("请输入正确的验证码");
            return;
        }

        //判断密码
        if (TextUtils.isEmpty(first_password)) {
            til_first_password.setErrorEnabled(true);
            til_first_password.setError("密码不能为空");
            return;
        }
        if (TextUtils.isEmpty(second_password)) {
            til_second_password.setErrorEnabled(true);
            til_second_password.setError("密码不能为空");
            return;
        }

        if (!TextUtils.equals(first_password, second_password)) {
            til_first_password.setErrorEnabled(true);
            til_second_password.setErrorEnabled(true);
            til_first_password.setError("两次密码不一致");
            til_second_password.setError("两次密码不一致");
            return;
        }

        SMSSDK.submitVerificationCode("86", phone, auto_code);
    }

    private void isUserExist(final String phone) {
        HttpUtils.getFriendRequest(phone, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                DialogUtils.clearAlerDialog();
                Log.e(TAG, e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String content = response.body().string();

                Gson gson = new Gson();
                ResultJson json = gson.fromJson(content, ResultJson.class);
                if (json.getCode() == HttpUtils.SUCCESS_NO_CONTENT) {
                    EMUtils.registerIM(phone, et_first_password.getText().toString(), false);
                } else if (json.getCode() == HttpUtils.SUCCESS) {
                    DialogUtils.clearAlerDialog();
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(RegisterActivity.this, "该用户已存在", Toast.LENGTH_SHORT).show();
                        }
                    });
                }

            }
        });
    }


    /**
     * 显示dialog
     */
    private void showAlterDialog() {
        finish();
        Toast.makeText(this, "注册成功", Toast.LENGTH_SHORT).show();
    }


    /**
     * 判断是否是有有效手机号码
     *
     * @param str
     * @return
     */
    public boolean isMobile(String str) {
        Pattern p;
        Matcher m;
        boolean b;
        p = Pattern.compile("^[1][3,5,6,7,8][0-9]{9}$"); // 验证手机号
        m = p.matcher(str);
        b = m.matches();
        return b;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void showAlterDialog(ShowAlterDialog dialog) {
        showAlterDialog();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
        EventBus.getDefault().unregister(this);
    }

    public static class ShowAlterDialog {
    }
}
